package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.ReleaseStatus;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.attr.AttrValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo> implements RoomInfoService {

    @Autowired
    private RoomAttrValueMapper roomAttrValueMapper;

    @Autowired
    private RoomFacilityMapper roomFacilityMapper;

    @Autowired
    private RoomLabelMapper roomLabelMapper;

    @Autowired
    private RoomPaymentTypeMapper roomPaymentTypeMapper;

    @Autowired
    private RoomLeaseTermMapper roomLeaseTermMapper;

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private ApartmentInfoService apartmentInfoService;

    @Autowired
    private RoomAttrValueService roomAttrValueService;

    @Autowired
    private RoomFacilityService roomFacilityService;

    @Autowired
    private RoomLabelService roomLabelService;

    @Autowired
    private LabelInfoService labelInfoService ;

    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService ;

    @Autowired
    private PaymentTypeService paymentTypeService ;

    @Autowired
    private RoomLeaseTermService roomLeaseTermService ;

    @Autowired
    private LeaseTermService leaseTermService ;

    @Override
    public List<RoomInfo> listBasicByApartmentId(Long id) {
        // 创建查询条件
        LambdaQueryWrapper<RoomInfo> queryWrapper = new LambdaQueryWrapper<>();
        // 根据公寓ID查询
        queryWrapper.eq(RoomInfo::getApartmentId, id);
        // 只查询未删除的数据
        queryWrapper.eq(RoomInfo::getIsDeleted, 0);
        // 可以根据需要添加其他条件，如按房间号排序
        queryWrapper.orderByAsc(RoomInfo::getRoomNumber);

        // 执行查询并返回结果
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIdCustom(Long id) {
        // 1. 删除房间基本信息
        boolean roomResult = removeById(id);
        if (!roomResult) {
            return false;
        }

        // 2. 删除房间属性值关联
        LambdaQueryWrapper<RoomAttrValue> attrWrapper = new LambdaQueryWrapper<>();
        attrWrapper.eq(RoomAttrValue::getRoomId, id);
        roomAttrValueService.remove(attrWrapper);

        // 3. 删除房间配套设施关联
        LambdaQueryWrapper<RoomFacility> facilityWrapper = new LambdaQueryWrapper<>();
        facilityWrapper.eq(RoomFacility::getRoomId, id);
        roomFacilityService.remove(facilityWrapper);

        // 4. 删除房间标签关联
        LambdaQueryWrapper<RoomLabel> labelWrapper = new LambdaQueryWrapper<>();
        labelWrapper.eq(RoomLabel::getRoomId, id);
        roomLabelService.remove(labelWrapper);

        // 5. 删除房间支付方式关联
        LambdaQueryWrapper<RoomPaymentType> paymentWrapper = new LambdaQueryWrapper<>();
        paymentWrapper.eq(RoomPaymentType::getRoomId, id);
        roomPaymentTypeService.remove(paymentWrapper);

        // 6. 删除房间租期关联
        LambdaQueryWrapper<RoomLeaseTerm> leaseTermWrapper = new LambdaQueryWrapper<>();
        leaseTermWrapper.eq(RoomLeaseTerm::getRoomId, id);
        roomLeaseTermService.remove(leaseTermWrapper);

        return true;
    }

    @Override
    public boolean updateReleaseStatusById(Long id, ReleaseStatus status) {
        if (id == null || status == null) {
            return false;
        }

        // 构建更新实体
        RoomInfo roomInfo = new RoomInfo();
        roomInfo.setId(id);
        roomInfo.setIsRelease(status);

        // 执行更新操作，只更新isRelease字段
        return this.updateById(roomInfo);
    }

    //分页查询(带条件可选)
    @Override
    public IPage<RoomItemVo> pageRoomItem(Page<RoomItemVo> pageParam, RoomQueryVo queryVo) {
        // 通过自定义SQL查询房间列表
        return baseMapper.pageRoomItem(pageParam, queryVo);

    }

    //保存或更新
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveOrUpdateCustom(RoomSubmitVo roomSubmitVo) {
        //思路:有id值就先更新一下基本信息, 没id就新增. 更新就先全删一遍再存, 保存就直接保存不用删
        // 1. 保存或更新房间基本信息
        boolean isUpdate = roomSubmitVo.getId() != null && roomSubmitVo.getId() > 0;
        if (isUpdate) {
            // 更新房间基本信息
            this.updateById(roomSubmitVo);
        } else {
            // 新增房间基本信息
            this.save(roomSubmitVo);
        }

        Long roomId = roomSubmitVo.getId();

        // 如果是更新操作，先删除房间关联的所有数据
        if (isUpdate) {
            // 以下操作也都会加入到主事务
            // 使用逻辑删除，将is_deleted设为1
            roomAttrValueMapper.deleteByRoomId(roomId);
            roomFacilityMapper.deleteByRoomId(roomId);
            roomLabelMapper.deleteByRoomId(roomId);
            roomPaymentTypeMapper.deleteByRoomId(roomId);
            roomLeaseTermMapper.deleteByRoomId(roomId);
            graphInfoMapper.deleteByRoomId(roomId);
        }

        // 2. 保存房间图片信息
        saveRoomImages(roomId, roomSubmitVo.getGraphVoList());

        // 3. 保存房间属性值关联
        saveRoomAttrValues(roomId, roomSubmitVo.getAttrValueIds());

        // 4. 保存房间配套设施关联
        saveRoomFacilities(roomId, roomSubmitVo.getFacilityInfoIds());

        // 5. 保存房间标签关联
        saveRoomLabels(roomId, roomSubmitVo.getLabelInfoIds());

        // 6. 保存房间支付方式关联
        saveRoomPaymentTypes(roomId, roomSubmitVo.getPaymentTypeIds());

        // 7. 保存房间租期关联
        saveRoomLeaseTerms(roomId, roomSubmitVo.getLeaseTermIds());

        return roomId;
    }

    /**
     * 保存房间图片信息
     */
    private void saveRoomImages(Long roomId, List<GraphVo> graphVoList) {
        if (CollectionUtils.isEmpty(graphVoList)) {
            return;
        }

        List<GraphInfo> imageList = new ArrayList<>();
        for (int i = 0; i < graphVoList.size(); i++) {
            GraphVo graphVo = graphVoList.get(i);
            GraphInfo roomImage = new GraphInfo();
            roomImage.setId(roomId);
            roomImage.setName(graphVo.getName());
            roomImage.setUrl(graphVo.getUrl());
            imageList.add(roomImage);
        }
        if (!imageList.isEmpty()) {
            graphInfoMapper.insertBatch(imageList);
        }
    }

    /**
     * 保存房间属性关联
     */
    private void saveRoomAttrValues(Long roomId, List<Long> attrValueIds) {
        if (CollectionUtils.isEmpty(attrValueIds)) {
            return;
        }

        List<RoomAttrValue> attrValueList = new ArrayList<>();
        for (Long attrValueId : attrValueIds) {
            RoomAttrValue roomAttrValue = RoomAttrValue.builder()
                    .roomId(roomId)
                    .attrValueId(attrValueId)
                    .build();
            attrValueList.add(roomAttrValue);
        }

        if (!attrValueList.isEmpty()) {
            roomAttrValueMapper.insertBatch(attrValueList);
        }
    }

    /**
     * 保存房间配套设施关联
     */
    private void saveRoomFacilities(Long roomId, List<Long> facilityIds) {
        if (CollectionUtils.isEmpty(facilityIds)) {
            return;
        }

        List<RoomFacility> facilityList = facilityIds.stream()
                .map(facilityId -> RoomFacility.builder()
                        .roomId(roomId)
                        .facilityId(facilityId)
                        .build())
                .collect(Collectors.toList());

        if (!facilityList.isEmpty()) {
            roomFacilityMapper.insertBatch(facilityList);
        }
    }

    /**
     * 保存房间标签关联
     */
    private void saveRoomLabels(Long roomId, List<Long> labelIds) {
        if (CollectionUtils.isEmpty(labelIds)) {
            return;
        }

        List<RoomLabel> labelList = labelIds.stream()
                .map(labelId -> RoomLabel.builder()
                        .roomId(roomId)
                        .labelId(labelId)
                        .build())
                .collect(Collectors.toList());

        if (!labelList.isEmpty()) {
            roomLabelMapper.insertBatch(labelList);
        }
    }

    /**
     * 保存房间支付方式关联
     */
    private void saveRoomPaymentTypes(Long roomId, List<Long> paymentTypeIds) {
        if (CollectionUtils.isEmpty(paymentTypeIds)) {
            return;
        }

        List<RoomPaymentType> paymentTypeList = paymentTypeIds.stream()
                .map(paymentTypeId -> RoomPaymentType.builder()
                        .roomId(roomId)
                        .paymentTypeId(paymentTypeId)
                        .build())
                .collect(Collectors.toList());

        if (!paymentTypeList.isEmpty()) {
            roomPaymentTypeMapper.insertBatch(paymentTypeList);
        }
    }

    /**
     * 保存房间租期关联
     */
    private void saveRoomLeaseTerms(Long roomId, List<Long> leaseTermIds) {
        if (CollectionUtils.isEmpty(leaseTermIds)) {
            return;
        }


        List<RoomLeaseTerm> leaseTermList = leaseTermIds.stream()
                .map(leaseTermId -> RoomLeaseTerm.builder()
                        .roomId(roomId)
                        .leaseTermId(leaseTermId)
                        .build())
                .collect(Collectors.toList());

        if (!leaseTermList.isEmpty()) {
            roomLeaseTermMapper.insertBatch(leaseTermList);
        }
    }

    @Override
    public RoomDetailVo getDetailByIdCustom(Long id) {
        //1.获取房间的基本信息
        RoomInfo roomInfo = this.getById(id);

        RoomDetailVo roomDetailVo = new RoomDetailVo();
        BeanUtils.copyProperties(roomInfo, roomDetailVo);


        //获取公寓信息
        //获取房间所属公寓的id
        Long apartmentId = roomInfo.getApartmentId();
        //通过公寓id获取公寓所有信息
        ApartmentInfo apartmentInfo = apartmentInfoService.getById(apartmentId);
        //把查出来的公寓放进roomDetailVo, 下面所有代码逻辑都一样
        roomDetailVo.setApartmentInfo(apartmentInfo);


        //获取图片
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, 2);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, roomInfo.getId());
        List<GraphInfo> graphInfos = graphInfoMapper.selectList(graphInfoLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(graphInfos)) {
            ArrayList<GraphVo> graphVoss = new ArrayList<>();
            roomDetailVo.setGraphVoList(graphVoss);
        } else {
            ArrayList<GraphVo> graphVos = new ArrayList<>();
            for (GraphInfo graphInfo : graphInfos) {
                GraphVo graphVo = new GraphVo();
                BeanUtils.copyProperties(graphInfo, graphVo);
                graphVos.add(graphVo);
            }
            roomDetailVo.setGraphVoList(graphVos);
        }


        //属性信息列表
        LambdaQueryWrapper<RoomAttrValue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoomAttrValue::getRoomId, roomInfo.getId())
                .eq(RoomAttrValue::getIsDeleted, 0);
        List<RoomAttrValue> attrValueList = roomAttrValueService.list(wrapper);

        if (CollectionUtils.isEmpty(attrValueList)) {
            ArrayList<AttrValueVo> attrValueVos = new ArrayList<>();
            roomDetailVo.setAttrValueVoList(attrValueVos);
        } else {
            List<AttrValueVo> attrValueVoList = new ArrayList<>();
            for (RoomAttrValue roomAttrValue : attrValueList) {
                AttrValueVo attrValueVo = new AttrValueVo();
                BeanUtils.copyProperties(roomAttrValue, attrValueVo);
                attrValueVoList.add(attrValueVo);
            }
            roomDetailVo.setAttrValueVoList(attrValueVoList);
        }

        //配套信息列表
        LambdaQueryWrapper<RoomFacility> infoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        infoLambdaQueryWrapper.eq(RoomFacility::getRoomId, roomInfo.getId())
                .eq(RoomFacility::getIsDeleted, 0);
        List<RoomFacility> roomFacilityList = roomFacilityService.list(infoLambdaQueryWrapper);

        if (CollectionUtils.isEmpty(roomFacilityList)) {
            ArrayList<FacilityInfo> facilityInfos = new ArrayList<>();
            roomDetailVo.setFacilityInfoList(facilityInfos);
        } else {
            List<FacilityInfo> facilityInfoList = new ArrayList<>();
            for (RoomFacility roomFacility : roomFacilityList) {
                FacilityInfo facilityInfo = new FacilityInfo();
                BeanUtils.copyProperties(roomFacility, facilityInfo);
                facilityInfoList.add(facilityInfo);
            }
            roomDetailVo.setFacilityInfoList(facilityInfoList);
        }

        // 6. 获取房间标签信息
        LambdaQueryWrapper<RoomLabel> labelWrapper = new LambdaQueryWrapper<>();
        labelWrapper.eq(RoomLabel::getRoomId, roomInfo.getId())
                .eq(RoomLabel::getIsDeleted, 0);
        List<RoomLabel> roomLabelList = roomLabelService.list(labelWrapper);

        if (CollectionUtils.isEmpty(roomLabelList)) {
            ArrayList<LabelInfo> labelInfos = new ArrayList<>();
            roomDetailVo.setLabelInfoList(labelInfos);
        } else {
            List<Long> labelIds = roomLabelList.stream()
                    .map(RoomLabel::getLabelId)
                    .collect(Collectors.toList());

            // 查询标签信息
            List<LabelInfo> labelInfoList = labelInfoService.listByIds(labelIds);
            roomDetailVo.setLabelInfoList(labelInfoList);
        }

        //支付方式列表
        // 7. 获取房间支付方式
        LambdaQueryWrapper<RoomPaymentType> paymentWrapper = new LambdaQueryWrapper<>();
        paymentWrapper.eq(RoomPaymentType::getRoomId, roomInfo.getId())
                .eq(RoomPaymentType::getIsDeleted, 0);
        List<RoomPaymentType> roomPaymentTypeList = roomPaymentTypeService.list(paymentWrapper);

        if (CollectionUtils.isEmpty(roomPaymentTypeList)) {
            ArrayList<PaymentType> paymentTypes = new ArrayList<>();
            roomDetailVo.setPaymentTypeList(paymentTypes);
        } else {
            List<Long> paymentTypeIds = roomPaymentTypeList.stream()
                    .map(RoomPaymentType::getPaymentTypeId)
                    .collect(Collectors.toList());

            // 查询支付方式信息
            List<PaymentType> paymentTypeList = paymentTypeService.listByIds(paymentTypeIds);
            roomDetailVo.setPaymentTypeList(paymentTypeList);
        }


        // 8. 获取房间可选租期
        LambdaQueryWrapper<RoomLeaseTerm> leaseTermWrapper = new LambdaQueryWrapper<>();
        leaseTermWrapper.eq(RoomLeaseTerm::getRoomId, roomInfo.getId())
                .eq(RoomLeaseTerm::getIsDeleted, 0);
        List<RoomLeaseTerm> roomLeaseTermList = roomLeaseTermService.list(leaseTermWrapper);

        if (CollectionUtils.isEmpty(roomLeaseTermList)) {
            ArrayList<LeaseTerm> leaseTerms = new ArrayList<>();
            roomDetailVo.setLeaseTermList(leaseTerms);
        } else {
            List<Long> leaseTermIds = roomLeaseTermList.stream()
                    .map(RoomLeaseTerm::getLeaseTermId)
                    .collect(Collectors.toList());

            // 查询租期信息
            List<LeaseTerm> leaseTermList = leaseTermService.listByIds(leaseTermIds);
            roomDetailVo.setLeaseTermList(leaseTermList);
        }

        return roomDetailVo;
    }
}




